/* Copyright By Schips, All Rights Reserved
#    https://gitee.com/schips/
#
#    File Name:  mymodule.c
#    Created  :  2020-05-13 09:19:51
#    Usage    : 
#               insmod modulexx.ko 
#           or
#               insmod modulexx.ko devmaj=123 devmin=1 
#           then
#               cat /proc/devices
*/

#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/moduleparam.h>
static int devmaj = 0;
static int devmin = 0;
dev_t dev;
static int __init initializiton_function(void)
{
    int err;
    int conunt = 1;
    // for alloc dev
    int firstminor = 0;

    if(devmaj)
    {
        dev = MKDEV(devmaj, devmin);
        err = register_chrdev_region(dev, conunt, "static-cdev");
    }else
    {
        err = alloc_chrdev_region(&dev, firstminor, conunt, "dynamic-cdev");
    }

    if(err)
        printk(KERN_EMERG "register_chrdev_region failed\n");

    printk(KERN_EMERG "register_chrdev_region success\n");
    // 初始化代码
    printk(KERN_EMERG "[Done] initializiton_function\n");
    return 0;
}
static void __exit cleanup_function(void)
{
    // 清除代码
    printk(KERN_EMERG "cleanup_function\n");
    unregister_chrdev_region(dev, 1);
    printk(KERN_EMERG "unregister_chrdev_region\n");
}

module_init(initializiton_function); // 如果没有这个定义，初始化函数永远不会被调用
module_exit(cleanup_function); //
module_param(devmaj, int, 0644);
module_param(devmin, int, 0644);
MODULE_AUTHOR("Schips");        // 模块作者
MODULE_DESCRIPTION("Just a module");   // 模块描述
MODULE_LICENSE("GPL");
